package com.blazegame.logging.log4j;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.apache.log4j.LogManager;

import com.blazegame.logging.Logger;
import com.blazegame.logging.LoggerFactory;

/**
 * Creates log4j-backed loggers
 * 
 * @author JackChu
 * @version 1.0.0 2012-2-2 上午9:41:35
 */
public class Log4jLoggerFactory extends LoggerFactory {

	// key: name (String), value: a Log4jLogger;
	Map<String, Logger> loggerMap;

	public Log4jLoggerFactory() {
		loggerMap = new ConcurrentHashMap<String, Logger>();
	}

	@Override
	protected Logger getLoggerImpl(Class<?> cls) {
		return getLoggerImpl(cls.getName());
	}

	@Override
	protected Logger getLoggerImpl(String name) {
		Logger logger = null;
		// protect against concurrent access of loggerMap
		synchronized (this) {
			logger = (Logger) loggerMap.get(name);
			if (logger == null) {
				org.apache.log4j.Logger log4jLogger;
				if (name.equalsIgnoreCase(Logger.ROOT_LOGGER_NAME)) {
					log4jLogger = LogManager.getRootLogger();
				} else {
					log4jLogger = LogManager.getLogger(name);
				}
				logger = new Log4jLogger(log4jLogger);
				loggerMap.put(name, logger);
			}
		}
		return logger;
	}

}
